package com.iMusic.presentationLayer;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.iMusic.businessLogicLayer.Account;
import com.iMusic.businessLogicLayer.Cart;
import com.iMusic.businessLogicLayer.Staff;
import com.iMusic.util.UserMessages;

public class Login extends HttpServlet {

	
	/*
	 * Define Account (only with username and password)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Account account = new Account();
		String redirection = "default.jsp";
		
		HttpSession session = request.getSession();
		
		account.setUsername((String) request.getParameter("username"));
		account.setPasswd((String) request.getParameter("password"));

		try {
			if (account.login()) {
				Cart cart = (Cart) session.getAttribute("Cart");
				session.removeAttribute("Error");
				session.removeAttribute("Staff");
				if (cart != null) {
					account.setCart(cart);
					cart.setAccount(account);
					session.setAttribute("Cart", cart);
				}
				session.setAttribute("Account", account);				
				System.out.println("User " + account.getUsername() + " logged in.");
				
			}
			else {
				
				Staff staff = new Staff();
				staff.setUsername((String) request.getParameter("username"));
				staff.setPasswd((String) request.getParameter("password"));
				
				if (staff.login()) {
					session.removeAttribute("Error");
					session.removeAttribute("Account");
					session.setAttribute("Staff", staff);
					redirection = "adminFS.jsp";
					System.out.println("Staff " + staff.getUsername() + " logged in.");
				}
				else {
					session.setAttribute("Error", UserMessages.LOGIN_NOK);
					redirection += "?error="+UserMessages.LOGIN_NOK;
				}
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		response.sendRedirect(redirection);
		
	}
	
}
